import requests
import json
# from love.settings import key_gaode
# from geopy.geocoders import Nominatim
# geolocator = Nominatim(user_agent="specify_your_app_name_here")
# location = geolocator.geocode("河北省秦皇岛市")

key_gaode = '8d429e19683685bec6fe29ae65de57a6'
def get_long_lat(ip):
    url_params={'key':key_gaode,'ip':ip,}
    res=requests.get('https://restapi.amap.com/v3/ip?parameters',params=url_params)
    data=res.text
    data=json.loads(data)
    if data['status']=='1':  #判断是否根据ip获取地理位置成功
        add = data['province']+data['city']
        add_dict={'key':key_gaode,'address':add}
        add_res = requests.get(
            'https://restapi.amap.com/v3/geocode/geo?parameters', params=add_dict)
        add_data = json.loads(add_res.text)
        if add_data['status']=='1':  #判断是否获取地理编码（经纬度）
            res_data = add_data['geocodes'][0]['location']
    return res_data

#根据地理位置获取地理编码（经纬度）
def get_local(add):
    add_dict={'key':key_gaode,'address':add}
    add_res = requests.get(
        'https://restapi.amap.com/v3/geocode/geo?parameters', params=add_dict)
    add_data=json.loads(add_res.text)
    if add_data['status']=='1':
        res_data=add_data['geocodes'][0]['location']
    return res_data

def distance(start,end_long,end_lat):
    end=end_long+','+end_lat
    res = requests.get('https://restapi.amap.com/v3/distance?parameters', params={'key': key_gaode, 'origins': start, 'destination':end})
    res_data=json.loads(res.text)
    if res_data['status'] == '0' and res_data['results'][0]['info']:
        return False
    else:
        return res_data['results'][0]['distance']


